'use client';

import { use, useEffect, useSyncExternalStore } from 'react';
import { OrderStore } from '../lib/store/interface/order';
import { useOrderStore } from '../lib/store/orderStore';
import { useRouter } from 'next/navigation';

let testObj = {
  a: 1,
};
function getSnapshot() {
  return testObj.a;
}

function subscribe(callback: () => void) {
  const timer = setInterval(() => {
    testObj.a++;
    callback();
  }, 2000);
  // window.addEventListener('online', callback);
  // window.addEventListener('offline', callback);
  // return () => {
  //   window.removeEventListener('online', callback);
  //   window.removeEventListener('offline', callback);
  // };
  return () => {
    timer && clearInterval(timer);
  };
}
export const OrderTable = ({
  initialRes,
}: {
  initialRes: Promise<{
    code: number;
    data?: OrderStore.OrderItem[];
    error?: any;
  }>;
}) => {
  const { setOrder, list } = useOrderStore();
  const addNum = useSyncExternalStore(subscribe, getSnapshot, () => 10);
  const router = useRouter();
  const initialWaitList = use(initialRes);
  useEffect(() => {
    if (
      initialWaitList.code === 0 &&
      initialWaitList.data &&
      list.length === 0
    ) {
      setOrder(initialWaitList.data);
    }
  }, [initialWaitList, setOrder]);

  const handleGotoDetail = (item: OrderStore.OrderItem) => {
    router.push(`/order/${item.id}`);
  };
  return (
    <div className='px-4'>
      <h1 className='font-bold text-main leading-12'>OrderTable{addNum}</h1>
      <ul>
        {list.map((item, index) => (
          <li
            key={item.id}
            onClick={() => handleGotoDetail(item)}
            className={
              'text-blue-600' +
              '/' +
              index * 25 +
              ' hover:text-blue-700 cursor-pointer'
            }
          >
            {item.name}
          </li>
        ))}
      </ul>
    </div>
  );
};
